/**
 * @Author: jipeng.Li
 * @Date: 2021-02-24 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-03 09:58:21
 * @Description: 油卡核销
 */
import React, { Component } from 'react';
import {
  View,
  SafeAreaView,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Image,
  NativeModules, Platform, BackHandler
} from 'react-native';
import { BackImage, Header, msg } from '@/common';
import {
  iconPositionCoffee,
  iconOilPriceAmount,
  iconOilNumber,
  iconDown
} from '@/images';
import {
  isAndroid,
  px2dp,
  fontColorBlack,
  fontColorCoffee,
  mainBgColorLightGray,
  mainBgColorWhite,
  splitLineColorLightGray, mainBgColorBlack
} from '@/styles';
import Picker from '@/common/picker';
import LinearGradient from 'react-native-linear-gradient';
import oilApi from '@/api/oil';
import api from '@/api';
import FictitiousOilCard from './components/fictitious-oil-card';

export default class OliCardWriteOff extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      oilOrderNo: '',
      writeOffPrice: '', // 核销金额
      oilNumber: '', // 油号
      oilNumberId: '',
      oilCardInfo: {
        caronwerCustName: '',
        allianceName: '',
        leaglName: '',
        total: '0.00',
        driverName: '',
        driverMobile: '',
        empowerNum: 0,
        carNo: '',
        empowerEndTime: '',
        allianceId: ''
      },
      stationRord: [],
      curStation: {},
      curOilNoList: []
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { id, oilOrderNo } = params;
    this.setState({ id, oilOrderNo }, () => this.getCurrentPosition());
    msg.on('curStation', (curStation) => {
      this.setState({ curStation }, () => this.getOilNo());
    });
    if (isAndroid) {
      BackHandler.addEventListener('hardwareBackPress', this.androidBack);
    }
  }

  componentWillUnmount() {
    msg.off('curStation');
    if (isAndroid) {
      BackHandler.removeEventListener(
        'hardwareBackPress',
        this.androidBack
      );
    }
  }

  androidBack = () => {
    this.goBack();
    return true;
  }

  render() {
    const { writeOffPrice, oilNumber, oilCardInfo, curOilNoList } = this.state;
    const abled = (!!writeOffPrice && (!!oilNumber || oilNumber == 0)) && curOilNoList.length > 0;
    return (
      <SafeAreaView style={styles.container}>
        {this.renderHead()}
        <View style={styles.writeOffContainer}>
          <View style={styles.oilCardContainer}>
            <FictitiousOilCard
              owner={oilCardInfo.caronwerCustName}
              companyType={oilCardInfo.allianceName}
              companyName={oilCardInfo.leaglName}
              oliCardNumber=''
              balance={oilCardInfo.nowAmount || oilCardInfo.total}
              renderBottomContent={this._renderOilCardTab}
            />
          </View>
          <View style={styles.writeOffHandleView}>
            <View
              style={{
                flex: 1,
                flexDirection: 'row',
                justifyContent: 'space-around',
                alignItems: 'center'
              }}
            >
              {/* 选择油号 */}
              <View style={styles.writeOffHandleContainer}>
                <View style={styles.writeOffHandleTitle}>
                  <Image
                    style={styles.writeOffHandleImage}
                    source={iconOilNumber}
                  />
                  <Text style={{ color: '#333232', fontSize: px2dp(32) }}>选择油号</Text>
                </View>
                <TouchableOpacity
                  onPress={this.showPicker}
                  style={styles.writeOffHandleTitle}
                >
                  <Text style={{ color: fontColorBlack }}>
                    <Text style={{ fontSize: px2dp(56) }}>{oilNumber}</Text>
                    <Text>#</Text>
                  </Text>
                  <Image
                    style={{ width: px2dp(20), height: px2dp(20) }}
                    source={iconDown}
                  />
                </TouchableOpacity>
              </View>
              {/* 核销金额 */}
              <View style={styles.writeOffHandleContainer}>
                <View style={styles.writeOffHandleTitle}>
                  <Image
                    style={styles.writeOffHandleImage}
                    source={iconOilPriceAmount}
                  />
                  <Text style={{ color: '#333232', fontSize: px2dp(32) }}>核销金额</Text>
                </View>
                <TextInput
                  style={styles.priceInput}
                  value={writeOffPrice}
                  keyboardType='decimal-pad'
                  onChangeText={text => {
                    let newText = text !== '' && text.substr(0, 1) === '.' ? '' : text;
                    newText = newText.replace(
                      /^0+[0-9]+/g,
                      '0'
                    ); // 不能以0开头输入
                    newText = newText.replace(/[^\d.]/g, ''); // 清除"数字"和"."以外的字符
                    newText = newText.replace(/\.{2,}/g, '.'); // 只保留第一个, 清除多余的
                    newText = newText.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3',); // 只能输入两个小数
                    newText = newText
                      .replace('.', '$#$')
                      .replace(/\./g, '')
                      .replace('$#$', '.');
                    let inpValue = this.state.writeOffPrice;
                    if (Number(newText) >= 100000) {
                      inpValue = '100000';
                    } else {
                      inpValue = newText;
                    }
                    this.setState({ writeOffPrice: inpValue });
                  }}
                  placeholder='0.00'
                />
              </View>
            </View>
            <View style={{ alignItems: 'center', marginTop: px2dp(30) }}>
              <TouchableOpacity
                disabled={!abled}
                onPress={this.submitBtn}
                style={[styles.defineBtn, !abled && { opacity: 0.5 }]}
              >
                <Text style={styles.defineBtnTest}>提交</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        {this.renderTipsView()}
      </SafeAreaView>
    );
  }

  // 自定义头部
  renderHead = () => {
    const { latitude, longitude, curStation, oilCardInfo, city } = this.state;
    return (
      <Header
        renderTitle={() => <Text style={styles.headTitleText}>用油核销</Text>}
        renderLeft={() => {
          return (
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={this.goBack}
              style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
            >
              <BackImage />
            </TouchableOpacity>
          );
        }}
        renderRight={() => {
          return (
            <TouchableOpacity
              onPress={() => {
                msg.emit('router: goToNext', {
                  routeName: 'AddOilLocale',
                  position: { latitude, longitude, city },
                  allianceId: oilCardInfo && oilCardInfo.allianceId
                });
              }}
              style={[
                styles.headRight,
                isAndroid ? { marginRight: 14 } : {}
              ]}
            >
              <Image
                style={styles.headRightImage}
                source={iconPositionCoffee}
              />
              <Text
                style={styles.headRightText}
                numberOfLines={1}
              >
                {curStation && curStation.oilStationName}
              </Text>
            </TouchableOpacity>
          );
        }}
      />
    );
  }

  goBack = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { oilOrderNo } = params;
    api.oil.backVerification({ pumpOilNo: oilOrderNo }).then(res => { }); // 提醒后端更改二维码
    msg.emit('router: goToNext', {
      routeName: 'Main',
    });
  }

  // 油卡底部
  _renderOilCardTab = () => {
    const { oilCardInfo } = this.state;
    const carType = oilCardInfo && oilCardInfo.type;
    if (carType === 1) return null;
    const { empowerEndTime, empowerNum } = oilCardInfo;
    const remainNum = empowerNum && empowerNum != null ? empowerNum : '--';
    const endDateString = empowerEndTime && empowerEndTime != null ? empowerEndTime.toString().substring(0, 11) : '--';
    return (
      <View style={styles.oilTabContainer}>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text numberOfLines={1} style={[styles.oilTabText, { flex: 1 }]}>
            授权司机：
            {oilCardInfo.driverName}
            (
            {oilCardInfo.driverMobile}
            )
          </Text>
          <Text style={styles.oilTabText}>
            剩余次数：
            {remainNum}
          </Text>
        </View>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text style={[styles.oilTabText, { width: px2dp(350) }]}>
            车牌：
            {oilCardInfo.carNo}
          </Text>
          <Text style={styles.oilTabText}>
            到期：
            {endDateString}
          </Text>
        </View>
      </View>
    );
  }

  // 油号选择框
  showPicker = () => {
    const { curOilNoList } = this.state;
    if (!curOilNoList.length) return msg.emit('app:tip', { text: '当前油站没有油号' });
    Picker.init({
      pickerTitleText: '选择油号',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: curOilNoList,
      onPickerConfirm: (pickedValue, pickedIndex) => { // 确定
        this.setState({ oilNumber: pickedValue.toString() });
      },
      onPickerCancel: (pickedValue, pickedIndex) => { // 取消
        Picker.hide();
      },
      onPickerSelect: (pickedValue, pickedIndex) => { // 选择

      },
    });
    Picker.show();
  }

  // 底部提示
  renderTipsView = () => {
    return (
      <View style={styles.tipsContainer}>
        <View style={styles.tipsTitle}>
          <LinearGradient
            colors={['#E5B867', '#BB934B']}
            style={styles.tipsFlag}
          />
          <Text style={styles.tipsTitleText}>核销流程：</Text>
        </View>
        <View style={{ marginVertical: px2dp(5) }}>
          <Text style={styles.tipsText}>1.扫描用户油品核销码</Text>
        </View>
        <View style={{ marginVertical: px2dp(5) }}>
          <Text style={styles.tipsText}>2.录入油号与核销金额，点击“提交”</Text>
        </View>
        <View style={{ marginVertical: px2dp(5) }}>
          <Text style={styles.tipsText}>3.扣款成功</Text>
        </View>
      </View>
    );
  }

  // 获取当前定位
  getCurrentPosition = () => {
    // 当前定位
    NativeModules.MapModule.getCurrentPosition().then((resPosition) => {
      if (resPosition.city) {
        this.setState({ ...resPosition }, () => {
          this.getOidcardDetail();
        });
      } else {
        msg.emit('app:tip', { text: '获取地理位置信息失败' });
      }
    });
  };

  // 获取油卡相关信息
  getOidcardDetail = () => {
    const { id } = this.state;
    oilApi.getAuthById({ id }).then(res => {
      if (res.success) {
        this.setState({ oilCardInfo: res.data }, () => {
          this.getOilStationList();
        });
      } else {
        msg.emit('app:tip', { text: res.msg || '网络异常' });
      }
    }).catch((err) => {
      console.log('err==>', err);
      msg.emit('app:tip', { text: err || '网络异常' });
    });
  }

  getOilStationList = () => {
    const { latitude, longitude, oilCardInfo } = this.state;
    const params = {
      lat: latitude,
      lgt: longitude,
      allianceId: oilCardInfo.allianceId
    };
    oilApi.stationRord(params).then(res => {
      if (res.success) {
        const stationList = res.data;
        if (stationList.length > 0) {
          this.setState({ stationRord: stationList, curStation: stationList[0] }, () => {
            this.getOilNo();
          });
        } else {
          NativeModules.WindowModule.showWindow({
            content: '您所在位置附近暂无油站',
            title: '提示',
            onlyRightBtn: '1'
          }, e => {
            this.goBack();
          });
        }
      } else {

      }
    });
  }

  getOilNo = () => {
    const { curStation } = this.state;
    oilApi.stationOil({ stationId: curStation.id || '' }).then(res => {
      if (res.success) {
        const oilList = res.data || [];
        this.setState({ curOilNoList: res.data || [], oilNumber: oilList.length ? oilList[0] : '' });
      }
    });
  }

  // 提交按钮
  submitBtn = () => {
    const { oilNumber, writeOffPrice, curStation, oilCardInfo, oilOrderNo } = this.state;
    const { nowAmount, total } = oilCardInfo;
    const syAmount = nowAmount || total || 0;

    if (parseFloat(writeOffPrice) <= 0) {
      this.setState({ modalIsShow: true, modalType: 'confirm' });
      return;
    }
    if (Number(writeOffPrice) > Number(syAmount)) return msg.emit('app:tip', { text: '余额不足,请先去申请拨油' });
    NativeModules.WindowModule.showWindow({
      title: '',
      content: `油号：${oilNumber}#   核销金额：${writeOffPrice}元`
    }, e => {
      if (e == 1) {
        const params = {
          id: oilCardInfo && oilCardInfo.id,
          pumpOilNo: oilOrderNo,
          accountCarownerId: oilCardInfo && oilCardInfo.accountCarownerId,
          carownerIdentity: oilCardInfo && oilCardInfo.carownerIdentity,
          oil: oilNumber,
          stationId: curStation.id || '',
          writeOffAmount: writeOffPrice
        };

        oilApi.driverVerification(params).then(res => {
          if (res.success) {
            msg.emit('router: goToNext', {
              routeName: 'WriteOffResult',
              result: 1
            });
          } else {
            msg.emit('app:tip', { text: res.msg });
            msg.emit('router: goToNext', {
              routeName: 'WriteOffResult',
              result: 0
            });
          }
        });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  headTitleText: {
    color: '#000',
    fontSize: 18,
    fontWeight: isAndroid ? '400' : 'bold',
  },
  headRight: {
    maxWidth: px2dp(250),
    flexDirection: 'row',
    alignItems: 'center',
  },
  headRightImage: {
    width: px2dp(32),
    height: px2dp(32),
    marginRight: px2dp(10)
  },
  headRightText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    // textAlign: 'right',
    paddingRight: px2dp(40 * 2)
  },
  writeOffContainer: {
    flex: 1,
    position: 'relative',
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(24),
    marginTop: px2dp(180),
    marginBottom: px2dp(280),
    marginHorizontal: px2dp(20)
  },
  oilCardContainer: {
    position: 'absolute',
    top: px2dp(-155),
    width: '100%',
    alignItems: 'center',
  },
  oilTabContainer: {
    height: px2dp(100),
    justifyContent: 'space-around',
    paddingHorizontal: px2dp(15)
  },
  oilTabText: {
    color: '#E6D6BB',
    fontSize: px2dp(24)
  },
  writeOffHandleView: {
    flex: 1,
    marginTop: px2dp(155),
    justifyContent: 'space-around',
    paddingVertical: px2dp(50)
  },
  writeOffHandleContainer: {
    height: px2dp(200),
    width: px2dp(200),
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  writeOffHandleTitle: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  writeOffHandleImage: {
    width: px2dp(40),
    height: px2dp(40),
    marginRight: px2dp(10)
  },
  defineBtn: {
    width: px2dp(640),
    height: px2dp(88),
    backgroundColor: fontColorCoffee,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(12)
  },
  defineBtnTest: {
    color: mainBgColorWhite,
    fontSize: px2dp(32)
  },
  tipsContainer: {
    height: px2dp(200),
    justifyContent: 'center',
    borderTopWidth: px2dp(2),
    borderTopColor: splitLineColorLightGray,
    marginHorizontal: px2dp(20)
  },
  tipsFlag: {
    width: px2dp(6),
    height: px2dp(24),
    marginRight: px2dp(10)
  },
  tipsTitle: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  tipsTitleText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    fontWeight: 'bold'
  },
  tipsText: {
    color: '#686764',
    fontSize: px2dp(28),
  },
  priceInput: {
    width: '100%',
    fontSize: px2dp(56),
    padding: 0,
    color: fontColorBlack,
    alignItems: 'center'
  },
});
